package com.unitd.modules.gen.controller;

import com.github.pagehelper.PageInfo;
import com.unitd.comm.web.BaseController;
import com.unitd.frame.comm.utils.BooleanUtils;
import com.unitd.frame.comm.utils.StringUtils;
import com.unitd.frame.springweb.controller.result.AjaxResult;
import com.unitd.frame.sso.annotation.Permission;
import com.unitd.modules.gen.entity.GenTemplate;
import com.unitd.modules.gen.service.IGenTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @desc 代码模板Controller
 * @filename GenTableController.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/4/27
 */
@Controller
@RequestMapping(value = "/gen/genTemplate")
public class GenTemplateController extends BaseController {

	@Autowired
	private IGenTemplateService genTemplateService;

	@ModelAttribute
	public GenTemplate get(@RequestParam(required = false) String id) {
		if (!StringUtils.isZero(id)) {
			return genTemplateService.selectByPrimaryKey(id);
		} else {
			return new GenTemplate();
		}
	}

	@Permission("gen:genTemplate:view")
	@RequestMapping(value = {"list", ""})
	public String list(GenTemplate genTemplate, HttpServletRequest request, HttpServletResponse response, Model model) {
		// 获取分页数据信息
		Map<String, Integer> pageMap = getPageMap();

		// 查询列表数据
		PageInfo<GenTemplate> page = genTemplateService.getPageData(pageMap.get("pageNo"), pageMap.get("pageSize"), genTemplate);
		model.addAttribute("page", page);
		return "modules/gen/genTemplateList";
	}

	@Permission("gen:genTemplate:view")
	@RequestMapping(value = "form")
	public String form(GenTemplate genTemplate, Model model) {
		model.addAttribute("genTemplate", genTemplate);
		return "modules/gen/genTemplateForm";
	}

	@Permission("gen:genTemplate:edit")
	@RequestMapping(value = "save")
	public AjaxResult save(GenTemplate genTemplate, Model model, RedirectAttributes redirectAttributes) {
		// 调用Hibernate-validate进行数据校验
		String validatMsg = beanValidator(model, genTemplate);
		if(!StringUtils.isNull(validatMsg)) {
			return new AjaxResult(false, "处理数据失败![" +validatMsg+"]");
		}

		genTemplateService.doEdit(genTemplate, getSSOToken().getUid());
		return new AjaxResult(true);
	}

	@Permission("gen:genTemplate:edit")
	@RequestMapping(value = "delete")
	public String delete(GenTemplate genTemplate, RedirectAttributes redirectAttributes) {
		genTemplateService.deleteByDelFlag(genTemplate);
		return BooleanUtils.toString(true);
	}
}